<template>
  <div>    
    <div id="chart"
         v-loading="loading"
         element-loading-text="数据获取中..."
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)"
        >
      <div>
          <el-menu
                  :default-active="activeIndex2"
                  class="el-menu-demo"
                  mode="horizontal"
                  @select="handleSelect"
                  background-color="#545c64"
                  text-color="#fff"
                  active-text-color="#ffd04b">
              <el-menu-item index="-1"> 概况</el-menu-item>
              <el-menu-item index="1"> 销售情况 </el-menu-item>
              <el-menu-item index="2"> 语音控制 </el-menu-item>
              <el-menu-item index="3"> 二维码扫码 </el-menu-item>
              <el-menu-item index="4"> ESP32-CAM拍照 </el-menu-item>
          </el-menu>
      </div>
      <div v-show="pagetype=='chart'">
        <div style="font-size: 20px;text-align: center;padding: 5px;">
          <vue-justgage ref="g1" id="g1" ></vue-justgage>
        </div>
        <div style="font-size: 20px;text-align: center;padding: 5px;">
          <div>最近销售情况</div>
          <canvas ref="barChart" width="30" height="20"></canvas>
        </div>
      </div>
      <div v-show="pagetype=='wavcontrol'">
          <el-button ref="soundctl" :icon="soundctlicon" type="primary" @mousedown.native="startwav()" @mouseup.native="sendwav()">{{ soundctltitle }}</el-button>
      </div>
      <div v-show="pagetype=='esp32-cam'">
          <el-button ref="esp32ctl" type="primary" @mousedown.native="camerashot()">拍照</el-button>
      </div>         
      <div v-show="pagetype=='jseq'">
          <canvas id="jsqrcanvas" width="100" height="100" hidden></canvas>
          <div>{{ jseqcode }} </div>
      </div>      
      <div v-show="pagetype=='goodsdetails'">
        <div id="ulist">
            <div style="width: 100%;padding: 6px;">
              <div style="float:left;width: 10%;">
                  <div align="center">
                      &nbsp;&nbsp;&nbsp;&nbsp;
                  </div>
              </div>
              <div style="float:left;width: 90%;">
                  <div align="center">
                      <div style="float:left;padding:10px;text-align: center;font-size: 15px;width: 25%;">
                          商品名称
                      </div>
                      <div style="float:left;padding:10px;text-align: center;font-size: 15px;width: 20%;">
                          商品价格
                      </div>
                      <div style="float:left;padding:10px;text-align: center;font-size: 15px;width: 20%;">
                          货道
                      </div>
                      <div style="float:left;padding:10px;text-align: center;font-size: 15px;width: 20%;">
                          剩余数量
                      </div>
                  </div>
              </div>
            </div>
            <div style="width: 100%">
              <section class="ulist clearfix" v-for="(item, index) in goodsorderdetails" :key="index">
                  <div class="info" style="text-align: center;">
                    <div style="float:left;width: 10%;">
                        <div align="center">
                            <el-image
                                    style="width: 50px; height: 50px;"
                                    :src="item.image">
                            </el-image>
                        </div>
                    </div>
                    <div style="float:left;width: 90%;">
                        <div align="center">
                            <div style="float:left;padding:15px 10px 10px 10px;text-align: center;font-size: 15px;width: 25%;">
                                {{ item.goodsname }}
                            </div>
                            <div style="float:left;padding:15px 10px 10px 10px;text-align: center;color:#F00;font-size: 15px;width: 20%;">
                                ￥{{ item.money }}
                            </div>
                            <div style="float:left;padding:15px 10px 10px 10px;text-align: center;color:#F00;font-size: 15px;width: 20%;">
                                {{ item.cargoway }}
                            </div>
                            <div style="float:left;padding:15px 10px 10px 10px;text-align: center;color:#F00;font-size: 15px;width: 20%;">
                                {{ item.curamount }}
                            </div>
                        </div>
                    </div>
                  </div>
              </section>
            </div>
        </div>
      </div>  
      <div>      
        <el-image 
          style="width: 100px; height: 100px"
          v-bind:src="demoimg" 
          v-bind:preview-src-list="srcList">
        </el-image>  
      </div>  
    </div>
    <Topnav></Topnav>
  </div>
</template>

<script>
import Vue from 'vue';
import mqtt from 'mqtt';
import Topnav from "./topnav.vue";  
import Chart from 'chart.js';
import axios from 'axios';  
import Recorder from 'js-audio-recorder';
import jsQR from "jsqr";
import Quagga from 'quagga';

let recorder = new Recorder({
    sampleBits: 16,         // 采样位数，支持 8 或 16，默认是16
    sampleRate: 16000,      // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
    numChannels: 1,         // 声道，支持 1 或 2， 默认是1
    compiling: false,       // 是否边录边转换，默认是false
});

export default {
  name: 'chart',
  data () {
    return {
       activeIndex2: '-1',
       chartdataList: [],
       machineid : 0,
       soundctlicon : '',
       demoimg:'',
       loading : false,
       srcList:[],
       esp32camstring : '',
       jseqcode : '我是二维码',
       soundctltitle : '按住说话',
       pagetype : 'chart',
       justgageclient: null,
       video:null,
       boolisjsqr:false,
       jsqrcanvas:null,
       canvasElement:null,
       canvas:null,
       barChart : null,
       goodsorderdetails: {
          type: Array,
          default: () => []
       },  
    }
  },
  components: {
    Topnav,
  },   
  mounted: function() { 
    this.machineid = this.$route.params.machineid;
    this.InitChart();
    this.InitMqtt();     
    this.getmachinegoodsselldetails();
    this.getmachinegoodsdayselldetails();
  }, 
  destroyed: function () {
    console.log("Chat leave.");
    this.$GLOBAL.mqttclient.end();
  },
  methods: {
    handleSelect(key, keyPath) {
        if(key == -1) {
          this.getmachinegoodsdayselldetails();
          this.pagetype = 'chart'; 
          this.CloseJsQR();
        }
        else if(key == 2) {
          this.pagetype = 'wavcontrol';
          this.CloseJsQR();
        }
        else if(key == 3) {
          this.pagetype = 'jseq';
          this.OpenJsQR();
        }
        else if(key == 4) {
          this.pagetype = 'esp32-cam';
        }

        else {
          this.getmachinegoodsselldetails();
          this.pagetype = 'goodsdetails';
          this.CloseJsQR();
        }
    },
    OpenJsQR() {
      var self = this;      

      this.video = document.createElement("video");
      this.canvasElement = document.getElementById("jsqrcanvas");
      this.canvas = this.canvasElement.getContext("2d");

      this.boolisjsqr = true;

      // Use facingMode: environment to attemt to get the front camera on phones
      navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" , width: 200,hegit: 200} }).then(function(stream) {
        self.video.srcObject = stream;
        self.video.setAttribute("playsinline", true); // required to tell iOS safari we don't want fullscreen
        self.video.play();
        requestAnimationFrame(self.JsQRtick);
      });
    },
    CloseJsQR() {
      if(this.boolisjsqr) {
        this.video.srcObject.getTracks()[0].stop();
        this.boolisjsqr=false;
      }
    },
    camerashot: function() {
       var qtt = {}; //定义消息（可以为字符串，对象等）
       qtt.action = "on";

       this.mqttclient.publish('takepicture',JSON.stringify(qtt),{ qos: 0, retain: false })
    },    
    JsQRtick() {
      var self = this;

      if (this.video.readyState === this.video.HAVE_ENOUGH_DATA) {
        this.canvasElement.hidden = false;

        this.canvasElement.height = this.video.videoHeight;
        this.canvasElement.width = this.video.videoWidth;
        this.canvas.drawImage(this.video, 0, 0, this.canvasElement.width, this.canvasElement.height);

        var dataURL = this.canvasElement.toDataURL('image/png');
        //console.log(dataURL);
        this.QuaggaImage(dataURL);

        /*const jsQR = require("jsqr");
        var imageData = this.canvas.getImageData(0, 0, this.canvasElement.width, this.canvasElement.height);
        var code = jsQR(imageData.data, imageData.width, imageData.height, {
          inversionAttempts: "dontInvert",
        });
        if (code) {
          this.jseqcode = code.data;
        } else {
          this.jseqcode = '我没识别到二维码';
        }*/
      }
      requestAnimationFrame(this.JsQRtick);
    },
    QuaggaImage(img_url) {
        var config = {
            inputStream: {
                size: 800,
                singleChannel: false
            },
            locator: {
                patchSize: "medium",
                halfSample: true
            },
            decoder: {
                readers: [{
                    format: "code_128_reader",
                    config: {}
                }]
            },
            locate: true,
            src: img_url
            /*src: ''*/
        };

        Quagga.decodeSingle(config, function (result) {
            console.log("解码中...");
            if (!result) {
                console.log("图片中没有条形码！");
                return false;
            }
            //识别结果
            if (result.codeResult) {
                console.log("图片中的条形码为：" + result.codeResult.code);
                alert(result.codeResult.code);
            } else {
                console.log("未识别到图片中的条形码！");
            }
        });
    },
    startwav() {
      this.soundctltitle = '正在说话';
      this.soundctlicon = 'el-icon-loading';

      recorder.start().then(() => {
          // 开始录音
      }, (error) => {
          // 出错了
          console.log('${error.name} : ${error.message}');
      });
    },
    sendwav() {
      this.soundctltitle = '按住说话';
      this.soundctlicon = '';

      recorder.stop();

      const data = new FormData();
      data.append('name','soundfile');
      data.append('file', recorder.getPCMBlob(),Date.parse(new Date())+'.pcm');
      data.append('news_type','pcm');

      axios.post('http://cms.o4.com/baiduspeechrecognition', data, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }).then(res => {
        console.log(res.data.result[0]);

        var location = 'http://cms.o4.com/chatrobot/msg/' + res.data.result[0];

        axios.get(location)
          .then(function (response) {
            console.log(response.data.msg);
            new Audio(
              'http://tts.baidu.com/text2audio?cuid=baiduid&lan=zh&ctp=1&pdt=311&tex='+response.data.msg
            ).play();
          })
          .catch(function (error) {
            console.log(error);
          });

        /*if(res.data.result[0].includes('回到首页')) {
          new Audio(
            'http://tts.baidu.com/text2audio?cuid=baiduid&lan=zh&ctp=1&pdt=311&tex='+res.data.result[0]
          ).play();

           this.$router.push({ path: '/Login' }); 
        }
        else if(res.data.result[0].includes('龟儿子')) {
          new Audio(
            'http://tts.baidu.com/text2audio?cuid=baiduid&lan=zh&ctp=1&pdt=311&tex=请注意您的说辞，不要随便骂人好不好！'
          ).play();
        }*/
      }).catch(err => {
        console.log(err);
      });
    },
    getmachinegoodsselldetails : function () {
      var self = this;

      var location = 'http://cms.o4.com/mobilegetmachinegoodsselldetails';

      var userinfo = this.$cookies.get('userinfo');
      axios.get(location, {
          params: {
            machineid:self.machineid
          }
        })
        .then(function (response) {        
          self.goodsorderdetails = response.data;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    getmachinegoodsdayselldetails : function () {
      var self = this;

      var location = 'http://cms.o4.com/mobilegetgoodsselldetails';

      var userinfo = this.$cookies.get('userinfo');
      axios.get(location, {
          params: {
            userid: userinfo.id,
            machineid:self.machineid
          }
        })
        .then(function (response) {        

          for(var i=0;i<response.data.length;i++) 
          {
             var tmp =response.data[i]['goodsmoney'];
             //console.log(tmp);
             self.chartdataList.unshift(tmp);
          }

          self.barChart.update();  
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    InitChart: function () {
      var self = this;

      var maxx = 100;

      this.justgageclient = this.$refs.g1.draw({
          id: "g1",
          value: 0,
          min: 0,
          max: maxx,
          titleMinFontSize:5,
          title: "机器温度",
          label: "",
          pointer: true,
          textRenderer: function (val) {
              return (val + '/' + maxx);
          },
          onAnimationEnd: function () {
              console.log('f: onAnimationEnd()');
          }
      });

      var ctx = this.$refs.barChart.getContext('2d');
      this.barChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ["上上上前天", "上上前天", "上前天", "昨天","今天"],
          datasets: [{
            label: '销售额',
            data: self.chartdataList,
            backgroundColor: [
              'rgba(255, 99, 132, 0.6)',
              'rgba(54, 162, 235, 0.6)',
              'rgba(255, 206, 86, 0.6)',
              'rgba(75, 192, 192, 0.6)',
              'rgba(153, 102, 255, 0.6)'
            ]
          }]
        }
      });
    },
    InitMqtt: function () {
      var self = this;

       var options = {
      //mqtt客户端的id，这里面应该还可以加上其他参数，具体看官方文档
        clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 14),
        //username:'admin',
        //password:'112233',   
      }    

      this.mqttclient = mqtt.connect("ws://mq.tongxinmao.com:18832/mqtt",options) // you add a ws:// url here
      this.$GLOBAL.mqttclient = this.mqttclient;

      //建立连接
      this.mqttclient.on('connect', function () {
        console.log("中心服务器连接成功!")

        var subscribes = ['super/machine/gettemperature',
                          'home/photo/start',
                          'home/photo/data',
                          'home/photo/end'];

        //订阅主题 presence
        self.mqttclient.subscribe(subscribes, function (err) {
          if (!err) {
            console.log("中心服务器消息订阅成功!")
          }else{
          //打印错误
            console.log(err)
          }
        })          
      })
      
      //如果连接错误，打印错误
      this.mqttclient.on('error', function (err) {
        console.log(err)
        self.mqttclient.end()
      })

      //如果client订阅主题成功，那么这里就是当接收到自己订阅主题的处理逻辑
      this.mqttclient.on('message', function (topic, message) {
        // message is Buffer,此处就是打印消息的具体内容
        var msg = message.toString();
        var topicstr = topic.toString();

        if(topicstr == 'home/photo/data') {
           self.esp32camstring += msg;
           return; 
        }

        //console.log(topicstr + ":" + msg);

        var userinfo = self.$cookies.get('userinfo');

         try{ 
          var params = JSON.parse( message.toString() );

          if(topicstr == 'super/machine/gettemperature') {
            
            if(params.machine_id == self.machineid && params.playerid == userinfo.id)
            {
                self.justgageclient.refresh(params.temperature);
            }  
          }
          else if(topicstr == 'home/photo/start') {
            self.esp32camstring='data:image/jpeg;base64,';

            self.loading=true;      
          }
          else if(topicstr == 'home/photo/end') {
            //console.log(self.esp32camstring);
            self.demoimg = self.esp32camstring;
            self.srcList.push(self.demoimg);

            self.loading=false; 
          }          

         }catch(exception){
          console.info(exception.message);
         } 
      })
    }
  }     
}
</script>

<style>

</style>
